<template>
  <BasicModal @register="registerModal" @ok="handleSuccess">
    <BasicForm @register="registerForm">
      <template #avatar="{ model, field }">
        <Upload
          list-type="picture-card"
          :customRequest="customUpload"
          :show-upload-list="false"
          accept=".jpg, .png, .jpeg"
        >
          <img
            v-if="model[field]"
            :src="model[field]"
            alt="avatar"
            :style="{
              width: 102 + 'px',
              height: 102 + 'px',
            }"
          />
          <span v-else>上传头像</span>
        </Upload>
      </template>
    </BasicForm>
  </BasicModal>
</template>

<script setup lang="ts">
  import { ref, unref } from 'vue';
  import { useModalInner, BasicModal } from '/@/components/Modal';
  import { formSchema } from '/@/views/system/user/data';
  import { useForm, BasicForm } from '/@/components/Form';
  import { Upload } from 'ant-design-vue';
  import { uploadFIle } from '/@/api/sys/file';
  import { addUser, updateUser } from '/@/api/sys/user';

  const emits = defineEmits(['register', 'success']);
  const isUpdate = ref(false);
  const user_id = ref(0);
  const avatar = ref('');

  const [registerForm, { validate, setFieldsValue, resetFields }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    baseColProps: { span: 24 },
    showActionButtonGroup: false,
  });
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      user_id.value = data.record.id;
      await setFieldsValue({
        ...data.record,
        avatar: data.record.avatar_url,
      });
    }
  });

  async function customUpload(res) {
    console.log(res);
    let data = await uploadFIle(res.file);
    avatar.value = data.data.file;
    let file_url = data.data.file_url;
    await setFieldsValue({
      avatar: file_url,
    });
  }

  async function handleSuccess() {
    let value = await validate();
    setModalProps({ confirmLoading: true });
    value.avatar = avatar.value;
    if (unref(isUpdate)) {
      value.id = user_id.value;
      await updateUser(value);
    } else {
      await addUser(value);
    }
    setModalProps({ confirmLoading: false });
    closeModal();
    emits('success');
  }
</script>

<style scoped></style>
